/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.security.nls.support;

import com.google.common.base.Charsets;
import org.vacoor.nothing.common.util.IOUtils;
import org.vacoor.nothing.security.nls.Translator;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Locale;
import java.util.Properties;

/**
 * 谷歌翻译引擎
 * V2 要收费
 * 这里直接是从 translate.g.cn 搞的请求
 *
 * @author vacoor
 */
public class GoogleTickleTranslator extends TranslatorSupport {
    // http://developer.baidu.com/wiki/index.php?title=%E5%B8%AE%E5%8A%A9%E6%96%87%E6%A1%A3%E9%A6%96%E9%A1%B5/%E7%99%BE%E5%BA%A6%E7%BF%BB%E8%AF%91/%E7%BF%BB%E8%AF%91API
    static final String GOOGLE_API = "http://translate.google.cn/translate_a/single?client=t&sl=#SL#&tl=#TL#&hl=en" +
            "&dt=t" +   // 翻译
            "&ie=UTF-8&oe=UTF-8" +
            "&q=#Q#";

    private static final String ENCODING = "UTF-8";
    public static final Translator INSTANCE = new GoogleTickleTranslator();

    @Override
    public boolean accepts(Locale from, Locale to) {
        return true;
    }

    @Override
    protected String doTranslate(String text, Locale from, Locale to, Properties props) {
        LOG.debug("执行谷歌翻译: {}, {} -> {}", text, from, to);
        try {
            final URL url = new URL(GOOGLE_API.replace("#SL#", from.toString()).replace("#TL#", to.toString()).replace("#Q#", URLEncoder.encode(text, ENCODING)));

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.91 Safari/537.36");

            String json = IOUtils.readText(conn.getInputStream(), Charsets.UTF_8, true);
            // [[["Password","密码"]],,"zh-CN"]
            json = json.replaceAll("(\\[){3}\"|\",.*$", "");
            return json;

        } catch (IOException e) { /*ignore*/ }
        return null;
    }
}
